package shopping.web.servlet;

import shopping.domain.Cart;
import shopping.domain.CartItem;
import shopping.domain.Product;
import shopping.service.ProductService;
import shopping.utils.GlobalUtil;
import shopping.utils.RRHolder;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet(urlPatterns = "/cart")
public class CartServlet extends BaseServlet {
    /**
     * 添加购物项
     */
    protected void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //接受pid和count
        String pid = request.getParameter("pid");
        int count = GlobalUtil.mustInt(request.getParameter("count"),1);
        //查询库存，判断数量问题，模拟进行，假设数量大于10，就认为库存不足，返回失败信息。
        if(count > 10){
            fail("库存不足");
            return;
        }

        //将购物信息（购物项）添加到购物车中。
        //首先要获取购物车，正常逻辑想就是new一个购物车对象，但是一次回话可能会产生多次添加的动作，如果new的话，每次添加都使用新的购物车了
        //获取自己的购物车，从session中
        Cart cart = getCart();

        //设置购物项
        CartItem cartItem = new CartItem();
        //设置购物项的两个属性，数量和商品
        cartItem.setCount(count);
        //通过pid查询数据库来获取商品
        Product product = new ProductService().findById(pid);
        cartItem.setProduct(product);

        //将购物项放入购物车中
        cart.addItem(cartItem);
        //返回成功信息
        success();
    }

    /**
     * 获取购物车列表信息
     */
    protected void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Cart cart = getCart();
        success(cart);
    }
    /**
     * 删除购物项
     */
    protected void delItem(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取自己购物车
        Cart cart = getCart();

        //根据pid调用删除购物项方法
        String pid = request.getParameter("pid");
        cart.removeItem(pid);
        success();
    }
    /**
     * 清空购物车
     */
    protected void clear(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取自己购物车
        Cart cart = getCart();
        cart.clear();
        success();
    }

    /**
     * 获取购物车
     * @return  session中的购物车
     */
    protected Cart getCart() {
        //判断session中有没有购物车
        HttpSession session = RRHolder.getRequest().getSession();
        Cart cart = (Cart) session.getAttribute("cart");
        if (cart == null){
            cart = new Cart();
            session.setAttribute("cart",cart);
        }
        return cart;
    }
}
